$(function(){
    /**
     * 自动化备份数据表
     * 
     */ 
    // 全局变量
    var pageNo = 1,// 
        pageSize = 10,
        type = 0,
        id = $('input[name="id"]').val();
    init()
    // 初始化
    function init(){
        allClickEvent()
        getBackupTable()
    }
    // 所有点击事件
    function allClickEvent(){
        $('#addDataBtn').on('click', function(){
            $('input[name="id"]').val(0)
            $('#del').attr('disabled', false)
            $('#del').val(0)
            validateForm()
            getSourcelist()

            $('#sourceCopy').html('<select class="form-control" name="tableName" id="tableName"><select>')
            $('#fieldCopy').html('<select class="form-control" name="column" id="column"><option value="-1">请先选择源表</option><select>')
            
            $('#addDataModal .modal-title').html('添加备份数据表')
            $('#addDataModal').modal('show')
            //切换选择源表时
            $('#tableName').on('change', function(){
                $('#tableBakName').val($(this).find('option:checked').attr('rel'))
                if($(this).val() == -1){
                    $('#tableBakName').val('')
                    $('#column').html('<option value="-1">请先选择源表</option>')
                } else {
                    getDatabase($(this).val())
                }
            })
        })
        $('#addDataModal').on('hide.bs.modal', function(){
            clearForm()
        })
    }
    // 展示自动化数据备份列表
    function getBackupTable(pageNo){
        if(!pageNo)pageNo=1;
        $('#userList').tableAjaxLoader2(11);
        $.ajax({
            url: '../../dataBackup/getBackupTable',
            type: 'post',
            data: {
                startTime: '',
                endTime: '',
                tableName: '',
                type: type,
                pageNo: pageNo,
                pageSize: pageSize
            },
            success: function(data){
                if(data.status) {
                    yunNoty(data)
                    $('#backupTable').find('tbody').html('<tr><td colspan=\"11\" style=\"text-align:center;\"><i class=\"glyphicon glyphicon-warning-sign\"></i>  当前纪录为空！</td></tr>');
                    $('#dataBackupPage').html('');
                } else {
                    var html = [];
                    if(data.List && data.List.length > 0){
                        for(var i = 0; i < data.List.length;i++){
                            html.push('<tr id="'+ data.List[i].Id +'" sourceTableName="'+data.List[i].SourceTableName+'" backupTableName="'+data.List[i].BackupTableName+'" versionName="'+data.List[i].VersionName+'" backupLevel="'+data.List[i].BackupLevel+'" loopCount="'+data.List[i].LoopCount+'" delType="'+data.List[i].DelType+'" sourceType="'+data.List[i].SourceType+'">')
                            html.push('<td>'+ data.List[i].SourceTableName +'</td>')
                            html.push('<td>'+ data.List[i].BackupTableName +'</td>')
                            html.push('<td>'+ data.List[i].VersionName +'</td>')
                            html.push('<td>'+ data.List[i].BackupLevel +'</td>')
                            html.push('<td>'+ data.List[i].LoopCount +'</td>')
                            html.push('<td>'+ (data.List[i].CreateTime || '--') +'</td>')
                            html.push('<td>'+ (data.List[i].UpdateTime || '--') +'</td>')
                            html.push('<td>'+ (data.List[i].DelType || '--') +'</td>')
                            if(data.List[i].SourceType){ //是
                                html.push('<td>是</td>')
                            } else {
                                html.push('<td>否</td>')
                            }
                            html.push('<td><a><i rel="'+data.List[i].Id+'" class="timeTip edit-backup glyphicon glyphicon-pencil" title="" data-original-title="编辑"></i>&nbsp; <i rel="'+data.List[i].Id+'" backuptablename="'+data.List[i].BackupTableName+'" class="timeTip del-backup glyphicon glyphicon-trash" title="" data-original-title="删除"></i></a></td>')
                            html.push('</tr>')
                        }
                        $('#backupTable').find('tbody').html(html.join(''))
						//下面开始处理分页
						var options = {
							data: [data, 'List', 'total'],
							currentPage: data.currentPage,
							totalPages: data.totlePages,
							onPageClicked: function (event, originalEvent, type, page) {
                                pageNo = page
								getBackupTable(page);
							}
						};
						setPage('dataBackupPage',options);
                        $('.timeTip').tooltip();
                        deleteBackup()//删除
                        editBackup()//修改
                    } else {
                        $('#backupTable').find('tbody').html('<tr><td colspan=\"11\" style=\"text-align:center;\"><i class=\"glyphicon glyphicon-warning-sign\"></i>  当前纪录为空！</td></tr>');
                        $('#dataBackupPage').html('');
                    }
                }
            }
        })
    }
    // 获取源表、备份表
    function getSourcelist(){
        type = 1
        $.ajax({
            url: '../../dataBackup/getBackupTable',
            type: 'post',
            data: {
                startTime: '',
                endTime: '',
                tableName: '',
                type: type,
                pageNo: pageNo,
                pageSize: pageSize
            },
            success: function(data) {
                if(data.status) {
                    yunNoty(data)
                } else {
                    if(data.List && data.List.length > 0){
                        var sourceTable = [];
                        $('#tableName').html('<option value="">请选择源表</option>')
                        for(var i = 0;i < data.List.length;i++){
                            sourceTable.push('<option value="'+data.List[i].SourceTableName+'" rel="'+data.List[i].BackupTableName+'">'+data.List[i].SourceTableName+'</option>')
                        }
                        $('#tableName').append(sourceTable.join(''))
                    } else {
                        $('#tableName').html('<option>暂无源表</option>')
                    }
                }
            }
        })
    }
    // 获取条件字段
    function getDatabase(tableName){
        type = 2
        $.ajax({
            url: '../../dataBackup/getBackupTable',
            type: 'post',
            data: {
                startTime: '',
                endTime: '',
                tableName: tableName,
                type: type,
                pageNo: pageNo,
                pageSize: pageSize
            },
            success: function(data){
                if(data.status) {
                    yunNoty(data)
                } else {
                    if(data.List && data.List.length > 0){
                        var versionName = [];
                        for(var i = 0;i < data.List.length;i++){
                            versionName.push('<option value="'+data.List[i].VersionName+'">'+data.List[i].VersionName+'</option>')
                        }
                        $('#column').html(versionName.join(''))
                    } else {
                        $('#column').html('<option value="-1">请先选择源表</option>')
                    }
                }
            }
        })
    }
    // 添加自动化数据备份表
    function addBackup(){
        $('#del').attr('disabled', false)
        $.ajax({
            type: 'get',
            datatype: 'json',
            cache: false,//不从缓存中去数据
            url: encodeURI('../../dataBackup/insertBackupTable'),
            data: $("#addBackup").serialize(),
            success: function(data){
                if(data.status){
                    yunNoty(data);
                }else{
                    yunNoty(data);
                    type = 0;
                    getBackupTable(pageNo)
                    $('#addDataModal').modal('hide');
                }
            }
        });
    }
    // 修改自动化数据备份表
    function editBackup(){
        //编辑回填
        $('.edit-backup').on('click',function(){
            validateForm()
            var self = this,
                $tr = $(self).parents('tr');
            $('input[name="id"]').val($tr.attr('id'));
            $('#addDataModal .modal-title').html('修改备份数据表')
            $('#addDataModal').modal('show')

            $('#sourceCopy').html('<input type="text" readonly placeholder="请先选择源表" class="form-control tableNameCopy" name="tableName">')
            $('#fieldCopy').html('<input type="text" readonly placeholder="请先选择源表" class="form-control columnCopy" name="column">')
            $('.tableNameCopy').val($tr.attr('sourceTableName'))
            $('#tableBakName').val($tr.attr('backupTableName'))
            $('.columnCopy').val($tr.attr('versionName'))
            $('input[name="backupLevel"]').val($tr.attr('backupLevel'))
            $('input[name="loopCount"]').val($tr.attr('loopCount'))
            if($tr.attr('delType') == '已生效'){
                $('#del').val(0)
            } else {
                $('#del').val(1)
            }
            if($tr.attr('sourceType') == 1){// 是源表
                $('#del').attr('disabled', true)
            } else {
                $('#del').attr('disabled', false)
            }
        });
    }
    // 删除数据表
    function deleteBackup(){
        //单个删除
        $('.del-backup').on('click',function(){
            var self = this,
                $tr = $(self).parents('tr');
            if($tr.attr('sourceType') == 1){// 源表
                yunNotyError('该表为源表，不允许删除!')
            } else { 
                $(self).adcCreator(function() {
                    someonedel(self)
                });
            } 
        });
    }
    // 删除数据表调用接口
    function someonedel(item){
        $.ajax({
            url: encodeURI('../../dataBackup/deleteBackupTable?id='+$(item).attr('rel'))+'&bakname='+$(item).attr('backuptablename'),
            type: 'post',
            cache: false,//不从缓存中去数据
            success: function(data){
                if(data.status){
                    yunNoty(data)
                } else {
                    yunNoty(data)
                    type = 0;
                    getBackupTable()
                }
            }
        })
    }
    // 添加自动化数据表时表单校验
    function validateForm() {
        var addDataForm = $('#addBackup').validate({
            rules:{
                tableName:{
                    required: true
                },
                tableBakName:{
                    required: true
                },
                column:{
                    required: true
                },
                backupLevel:{
                    required: true,
                    number: true,
                    min: 3000000,
                    max: 50000000
                },
                loopCount:{
                    required: true,
                    number: true,
                    min: 100000,
                    max: 1000000
                },
                del:{
                    required: true
                }
            },
            messages:{
                tableName:{
                    required: '请选择源表！'
                },
                tableBakName:{
                    required: '请先选择源表！'
                },
                column:{
                    required: '请先选择源表！'
                },
                backupLevel:{
                    required: '请填写备份级别！',
                    number: '请输入纯数字！',
                    min: '备份级别不能少于3000000！',
                    max: '备份级别不能多于50000000！'
                },
                loopCount:{
                    required: '请填写单次备份数量！',
                    number: '请输入纯数字！',
                    min: '单次备份数量不能少于100000！',
                    max: '单次备份数量不能多于1000000！'
                },
                del:{
                    required: '请选择是否生效！'
                }
            },
            submitHandler: addBackup
        });
    }
    // 重置数据
    function clearForm(){
        $('.text-error').removeClass("text-error helper-font-small")
        $('#addBackup input[type="text"]').val('')
        $('#column').html('<option value="-1">请先选择源表</option>')
    }
})